﻿#include "battery_frame_deform.h"

// 使用 utf8 编码
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

// 动力电池框架变形检测

/// <summary>
/// 
/// </summary>
battery_frame_deform::battery_frame_deform()
{
	m_pFrameDet = nullptr;

}


/// <summary>
/// 
/// </summary>
battery_frame_deform::~battery_frame_deform()
{
	if (m_pFrameDet != nullptr)
	{
		m_pFrameDet->Release();
		m_pFrameDet = nullptr;
	}

}



/// <summary>
/// 
/// </summary>
/// <returns></returns>
void battery_frame_deform::init()
{
	m_pFrameDet = CreateDetObj(m_strFrameDetModelPath);
}

/// <summary>
/// 
/// </summary>
/// <param name="pData"></param>
void battery_frame_deform::execute(QSharedPointer<IMG_DATA> pData, int nBuffersize)
{
	IMG_DATA data = *pData;
	data.image = urlToPixmap(data.strUrl);
	saveImage(data);

	cv::Mat image = QImage2cvMat(data.image);
	int nDispId = data.nDispId;

	if (!image.data || m_pFrameDet == nullptr)
	{
		return;
	}


	std::vector<DetectResult> results;
	m_pFrameDet->Evaluate(image, results);

	// 保存图片
	saveImage(image, "框架(定位)", data, results.size());


	for (int i = 0; i < results.size(); i++)
	{
		DetectResult res = results[i];
		cv::Rect rect = res.box;
		rect &= cv::Rect(0, 0, image.cols, image.rows);//求交集
		cv::Mat image_roi = image(rect);

		std::vector<DetectResult> def_results;

		// 保存图片
		saveImage(image_roi, "框架缺陷", data, def_results.size());

		
		// 			if (m_pRectDefect != nullptr)
		// 			{
		// 				m_pRectDefect->Evaluate(image_roi, def_results);
		// 			}
			
		// 如果没检测到破损，则不发布破损相关的数据
		if (def_results.size() != 0)
		{
			// 返回结果到 kafka 
			_tagResults tagResults;
			tagResults.setImageData(data);
			tagResults.setResults("框架变形", def_results, res.box.x, res.box.y);

			QString strResultTopc = data.strTopicName + suffix_2;
			QString strResultData = tagResults.toJSon();

			pushKafka(strResultTopc, strResultData, data.strStationId);
		}

		

		QPainter painter(&data.image);
		painter.setBrush(QBrush(QColor(255, 0, 0, 50)));
		QPen pen(Qt::red);
		pen.setWidth(5);
		painter.setPen(pen);

		cv::Point point = getCenterPoint(rect);
		painter.drawRect(rect.tl().x, rect.tl().y, rect.width, rect.height);

		emit updateShow(data.nDispId, data.image, nBuffersize);
	}

	// 返回结果到 kafka 
	_tagResults tagResults;
	tagResults.setImageData(data);
	tagResults.setResults("框架", results);
	tagResults.setVersion(m_strFrameDetModelPath);

	QString strResultTopc = data.strTopicName + suffix_1;
	QString strResultData = tagResults.toJSon();

	pushKafka(strResultTopc, strResultData, data.strStationId);
}
